package com.newflypig.jblog.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.newflypig.jblog.model.Category;
import com.newflypig.jblog.service.CategoryService;

@Controller
@RequestMapping("/category")
public class CategoryController {
	
	@Resource(name="categoryService")
	private CategoryService categoryService;
	
	@RequestMapping(value="/categories",method=RequestMethod.GET)
	public String list(Model model){
		List<Category> categories=this.categoryService.findAll();
		model.addAttribute("categories",categories);
		return "category/list";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add(){
		return "category/add";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(String title){
		Category c=new Category();
		c.setTitle(title);
		this.categoryService.save(c);
		return "redirect:categories";
	}
	
	@RequestMapping(value="/{categoryId}/delete",method=RequestMethod.GET)
	public String delete(@PathVariable Integer categoryId){
		this.categoryService.deleteById(categoryId);
		return "redirect:/category/categories";
	}
	
	@RequestMapping(value="/{categoryId}/show",method=RequestMethod.GET)
	public String show(@PathVariable Integer categoryId,Model model){
		Category c=this.categoryService.findById(categoryId);
		model.addAttribute("category",c);
		return "category/show";
	}
	
	@RequestMapping(value="/{categoryId}/update",method=RequestMethod.GET)
	public String update(@PathVariable Integer categoryId,Model model){
		Category c=this.categoryService.findById(categoryId);
		model.addAttribute("category",c);
		return "category/update";
	}
	
	@RequestMapping(value="/{categoryId}/update",method=RequestMethod.POST)
	public String update(Category category){
		System.out.println(category.getTitle()+"          "+category.getCategoryId());
		this.categoryService.update(category);
		return "redirect:/category/categories";
	}
}
